<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加用户 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="showAddDialog">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUser(scope.row.id)"
            >
            </el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showRolesDialog(scope.row)"
              >
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="70px"
      >
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话:" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="70px"
      >
        <el-form-item label="用户名:">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话:" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setDialogVisible"
      width="30%"
      class="setRoles"
      @close="setDialogClosed"
    >
      <p>当前的用户: {{ userInfo.username }}</p>
      <p>当前的角色: {{ userInfo.role_name }}</p>
      <p>
        分配新的角色：
        <el-select v-model="selectId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRolesInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 邮箱的验证规则
    const checkEmail = (rule, value, callback) => {
      const regEmail =
        /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的邮箱!'))
    }

    // 手机号的验证规则
    const checkMobile = (rule, value, callback) => {
      const regEmail = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的手机号!'))
    }

    // 用户名校验
    const checkUsername = (rule, value, callback) => {
      const regUsername = /^[a-zA-Z0-9_-]$/
      if (regUsername.test(value)) return callback()

      callback(new Error('用户名校验，4到16位（(字母，数字，下划线，减号)'))
    }

    // 密码校验
    const checkPsw = (rule, value, callback) => {
      const regPsw =
        /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]/
      if (regPsw.test(value)) return callback()

      callback(
        new Error(
          '大写字母，小写字母，数字，特殊符号`@#$%个&*~(0-+=`中任意3项密码'
        )
      )
    }
    return {
      // 获取用列表的参数
      queryInfo: {
        // 查询参数
        query: '',
        // 当前页码值
        pagenum: 1,
        // 每页显示条数
        pagesize: 10
      },
      // 存储用户数据
      userList: [],
      // 总分页数
      total: 0,
      // 添加用户表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加对话框的显示与隐藏
      addDialogVisible: false,

      // 添加用户信息规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 5, message: '用户名控制在2~5位之间', trigger: 'blur' },
          { validate: checkUsername, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 8, validator: checkPsw }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          {
            min: 13,
            max: 18,
            message: '邮箱长度在6~18之间字符之间',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            message: '请输入正确的邮箱格式!',
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入用户电话', trigger: 'blur' },
          {
            min: 11,
            max: 11,
            message: '电话长度为11位',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            message: '请输入正确的电话格式!',
            trigger: 'blur'
          }
        ]
      },
      // 编辑对话框的的显示与隐藏
      editDialogVisible: false,
      // 存储编辑用户数据对象
      editForm: {},
      // 编辑用户信息规则
      editFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          {
            min: 13,
            max: 18,
            message: '邮箱长度在6~18之间字符之间',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            message: '请输入正确的邮箱格式!',
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          {
            min: 11,
            max: 11,
            message: '电话长度为11位',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            message: '请输入正确的电话格式!',
            trigger: 'blur'
          }
        ]
      },
      setDialogVisible: false,
      // 需要分配的角色信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: {},
      // 已选择的id值
      selectId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })

      if (res.meta.status !== 200) {
        return this.$message.error('获取用户数据失败！')
      }

      this.userList = res.data.users
      this.total = res.data.total
    },
    // 每页显示条数
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 添加对话框的显示
    showAddDialog() {
      this.addDialogVisible = true
    },
    // 添加用户
    addInfo() {
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return false
        const { data: res } = await this.$http.post('users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败!')
        } else if (res.meta.msg === '用户名已存在') {
          return this.$message.error('用户已存在,请勿重复添加!')
        }

        this.$message.success('添加用户成功!')
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    async userStateChanged(userInfo) {
      // console.log(userInfo)
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        userInfo.status = !res.meta.status
        return this.$message.error('更新状态失败！')
      }
      this.$message.success('更新状态成功！')
    },
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('获取用户信息失败!')
      }
      this.editForm = res.data
      // console.log(this.editForm)
      this.editDialogVisible = true
    },
    // 更新数据
    editInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return false
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户失败！')
        }

        this.$message.success('更新用户成功！')
        this.editDialogVisible = false
        this.getUserList()
        console.log(res)
      })
    },
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    async removeUser(id) {
      const confirm = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirm !== 'confirm') return this.$message.info('已取消删除')

      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功！')

      this.getUserList()
    },
    async showRolesDialog(role) {
      // 获取当前角色信息
      this.userInfo = role
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      console.log(this.rolesList)

      this.setDialogVisible = true
    },
    async saveRolesInfo() {
      if (!this.selectId) return this.$message.error('请选择需要分配的角色！')
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectId
        }
      )
      if (res.meta.status !== 200) return this.$message.error('更新角色失败！')

      this.$message.success('更新角色成功！')
      this.getUserList()
      this.setDialogVisible = false
    },
    setDialogClosed() {
      this.selectId = ''
      this.userInfo = {}
    }
  }
}
</script>
<style lang="less" scoped>
.el-card {
  margin: 15px 0;
  box-shadow: 0 0 0;
}
.el-table {
  margin-top: 15px;
}
.setRoles {
  p {
    width: 100%;
    font-size: 16px;
    margin: 10px 0;
  }
}
</style>
